<template>
	<view class="container" style="padding:10px">
		<uni-forms ref="baseForm" label-width="80px">
			<uni-forms-item label="姓名">
				<uni-easyinput v-model="userInfo.RealName" placeholder="请输入姓名" :disabled="buttonDisabled" />
			</uni-forms-item>
			<uni-forms-item label="手机号">
				<uni-easyinput v-model="userInfo.UserPhone" placeholder="请输入手机号" disabled="" :disabled="buttonDisabled" />
			</uni-forms-item>
			<uni-forms-item label="身份证号">
				<uni-easyinput v-model="userInfo.IdCard" placeholder="请输入身份证号" :disabled="buttonDisabled" />
			</uni-forms-item>
			<!-- 暂时不删除后续需要打开 -->
			<uni-forms-item label="身份证照">
				<view v-if="FrontIdPhoto!=''" class="idcardZheng" @click="checkImgbox('zheng')">
					<image style="width:100%;height:100%" :src="FrontIdPhoto" mode=""></image>
				</view>
				<view v-else class="idcardZheng" :class="{'active':FrontIdPhoto}">
					<view class="img" style="display: flex;justify-content: center;align-items: center;"
						@click="openImagePage('正面')">
						<image style="width:390rpx;height:200rpx;" src="../../static/user/zhengmian.png" mode=""></image>
					</view>
					<view class="imgText" style="border:1px solid green;">
						上传证件正面照
					</view>
				</view>
				<view v-if="ReverseIdOPhoto!=''" class="idcardFan" @click="checkImgbox('fan')">
					<image style="width:100%;height:100%" :src="ReverseIdOPhoto" mode=""></image>
				</view>
				<view v-else class="idcardFan" :class="{'active':ReverseIdOPhoto}">
					<view class="img" style="display: flex;justify-content: center;align-items: center;"
						@click="openImagePage('反面')">
						<image style="width:390rpx;height:200rpx;" src="../../static/user/fanmian.png" mode=""></image>
					</view>
					<view class="imgText" style="border:1px solid green;">
						上传证件反面照
					</view>
				</view>
			</uni-forms-item>
		</uni-forms>

		<button @click="realName" style="position: fixed;bottom: 20px;width: calc(100% - 20px);" :type="buttonType"
			:disabled="buttonDisabled">{{buttonContent}}</button>
	</view>
</template>

<script>
	import {
		regPhone,
		regIdCard
	} from '../../utils/regExp.js'
	export default {
		data() {
			return {
				// 按钮颜色类型
				buttonType: "primary",
				// 是否禁用按钮
				buttonDisabled: false,
				// 按钮中间文字
				buttonContent: "实名认证",
				uploadFlag: false,
				// 加载
				loading: false,
				// 身份证正面
				FrontIdPhoto: "",
				// 身份正反面
				ReverseIdOPhoto: "",
				// 是否禁止
				disabled: false,
				userInfo: {},
				// 传递过来的参数
				options: {},
				// 认证类型
				SignType: "",
				remark: "",
				// 是否认证了
				isFlag: false,
				token: "",
				userInfo: {}
			}
		},
		onLoad(options) {
			// 获取用户信息
			this.op()
			this.options = options
			this.userInfo = uni.getStorageSync('userInfo')
			let isFlag = uni.getStorageSync('flag')
			if (isFlag == true) {
				this.buttonContent = "已实名认证"
				this.buttonType = "default"
				this.buttonDisabled = true
			}
			// 身份证照片正反面回显
			if (this.userInfo.FrontIdPhoto) {
				this.FrontIdPhoto = this.userInfo.FrontIdPhoto
			}
			if (this.userInfo.ReverseIdOPhoto) {
				this.ReverseIdOPhoto = this.userInfo.ReverseIdOPhoto
			}
		},
		onShow() {
			console.log('显示show里的用户信息', uni.getStorageSync('userInfo'))
			// this.userInfo = uni.getStorageSync('userInfo')
			// 缓存获取认证方式
			this.SignType = uni.getStorageSync('type') || 0
			// 获取认证token
			this.getToken()
		},
		methods: {
			// 获取TOKEN
			async getToken() {
				await uni.request({
					url: this.$veriUrl + '/auth/VeriRecord/token?phone=' + this.userInfo.UserPhone,
					method: 'GET'
				}).then(result => {
					let [err, res] = result;
					if (res.data.code == 200) {
						this.token = JSON.parse(res.data.data).access_token
						console.log('realname页面偶去token', this.token)
					}else{
						uni.showToast({
							title:'当前实名认证不通过',
							icon:'none'
						})
					}
				})
			},
			// 身份证正反面上传
			openImagePage(type) {
				if (this.buttonDisabled == true) return this.$api.msg('已实名认证')
				let that = this;
				// 暂时不删除 
				// if (that.fileList.length >= 3) {
				// 	uni.showToast({
				// 		title: "最多支持3张图片",
				// 		icon: "none"
				// 	})
				// 	return;
				// }
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: function(res) {
						that.uploadImage(res.tempFilePaths, type)

					}
				});
			},
			// 图片上传
			uploadImage(tempFilePaths, type) {
				this.loading = true
				// 禁用商铺认证按钮
				this.disabled = true
				uni.showLoading({
					title: '图片上传中'
				});
				let _this = this;
				uni.uploadFile({
					// url: 'https://api.yoojet.com/Base_Manage/Upload/Filleimag', //接口地址
					url: 'https://api.yoojet.com/Base_Manage/Upload/UploadFileProductByForm', //接口地址
					header: {
						"token": uni.getStorageSync('token'),
					}, //请求token
					filePath: tempFilePaths[0],
					name: 'file',
					success: (res) => {
						uni.showToast({
							title: '已上传'
						});
						// 取消按钮加载
						this.loading = false
						this.disabled = false
						let data = JSON.parse(res.data);
						let thumbUrl = data.thumbUrl;
						console.log('打印上传的图片', thumbUrl, this.userInfo)
						if (type === '正面') {
							this.FrontIdPhoto = thumbUrl
						} else {
							this.ReverseIdOPhoto = thumbUrl
						}

						// // 选中图片
						// if (_this.fileList.indexOf(url) == -1) {
						// 	// 先清空  避免后续拼接多个图片   后续如果多图片上上传修改这里即可
						// 	_this.fileList=[]
						// 	_this.fileList.push(url);

						// }
						// uni.hideLoading();
						// // 隐藏上传图片区域
						// _this.uploadFlag = false
						// 暂时不删除   根据后续需要打开即可
						// if (_this.fileList.length >= 3) {
						// 	
						// } else {
						// 	_this.uploadFlag = true
						// }

					},
					fail: (err) => {
						uni.hideLoading();
					}
				});
			},
			//放大图片
			checkImgbox(type) {

				var that = this
				if (this.buttonDisabled == true) {
					let urls = ""
					let arr = []
					if (type === 'zheng') {
						urls = this.FrontIdPhoto
						arr[0] = this.FrontIdPhoto
					} else {
						urls = this.ReverseIdOPhoto
						arr[0] = this.ReverseIdOPhoto
					}
					// 说明当前使命已认证  放大图片
					// 放大预览  暂时不用删除
					uni.previewImage({
						urls: arr,
						current: 0
					});
					return
				}

				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: function(res) {
						that.uploadImage(res.tempFilePaths)
					}
				});
			},
			// 人脸识别
			facePass() {
				// uni.showLoading()
				uni.request({
					url: 'https://aip.baidubce.com/rpc/2.0/brain/solution/faceprint/verifyToken/generate?access_token=' +
						this.options.token,
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					data: {
						plan_id: '16384'
					}
				}).then(result => {
					uni.hideLoading()
					let [err, res] = result;
					if (err !== null) flag = true
					if (res.statusCode == 200) {
						let token = res.data.result.verify_token
						let successUrl = encodeURIComponent('https://bill.yoojet.com/#/pass/facePassLoading')
						let url =
							`token=${token}&successUrl=${successUrl}&failedUrl=https://bill.yoojet.com/#/pass/facePassError`
						let newUrl = encodeURIComponent(url)
						uni.navigateTo({
							url: '/pages/webView/facePass?url=' + newUrl + '&at=' + this.token + '&vt=' +
								token
						})
					}
				})
			},
			// 百度校验身份信息
			baiduPass(RealName, IdCard) {
				uni.showLoading({
					title: '校验中,请稍等'
				})
				uni.request({
					url: 'https://aip.baidubce.com/rest/2.0/face/v3/person/idmatch?access_token=' + this.token,
					method: 'POST',
					data: {
						"id_card_number": IdCard,
						"name": RealName
					},
					header: {
						'Content-Type': 'application/json' //配置请求头
					},
				}).then(res => {
					uni.hideLoading()
					if (res.length >= 2) {
						let result = res[1]
						if (result.data.error_code == 0) {
							this.isFlag = true
							uni.setStorageSync('flag', this.isFlag)
							this.certification()
						} else {
							uni.showToast({
								title: '校验失败,身份证号与姓名不匹配',
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: '校验失败,身份证号与姓名不匹配',
							icon: 'none'
						})
					}
				})
			},
			// 保存认证记录
			certification() {
				uni.request({
					url: this.$veriUrl + '/auth/VeriRecord',
					method: 'POST',
					data: {
						"phone": this.userInfo.UserPhone,
						"name": this.userInfo.RealName,
						"idNumber": this.userInfo.IdCard,
						"state": true,
						VeriType: this.SignType,
						remark: JSON.stringify(this.remark)
					}
				}).then(result => {

					let [err, res] = result;
					if (err !== null) flag = true
					if (res.data.code == 200) {
						// 存储身份证信息
						this.setIdCardRequest()
						uni.showToast({
							title: '验证成功',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							})
						}, 1000)
					} else {
						this.buttonDisabled = false
						this.buttonContent = '实名认证'
						uni.showToast({
							title:'当前实名认证不通过',
							icon: 'none'
						})
					}
				})
			},
			// 三要素
			threeEle() {
				uni.request({
					url: this.$veriUrl + '/auth/VeriRecord/auth3',
					method: 'POST',
					data: {
						"phone": this.userInfo.UserPhone,
						"name": this.userInfo.RealName,
						"idNumber": this.userInfo.IdCard,
						"state": true
					}
				}).then(result => {
					let [err, res] = result;
					if (err !== null) flag = true

					if (res.data.code == 200) {
						let resp = JSON.parse(res.data.data)
						if (resp.code == 0) {
							this.remark = resp
							this.options.flag = true
							this.certification()
						} else {
							this.buttonDisabled = false
							this.buttonContent = '实名认证'
							uni.showToast({
								// title: '验证失败,请检查身份信息是否正确',
								title: resp.desc,
								icon: 'none'
							})
						}
					} else {
						this.buttonDisabled = false
						this.buttonContent = '实名认证'
						uni.showToast({
							title: '验证失败,请尝试重新提交',
							icon: 'none'
						})
					}
				})
			},
			// 实名认证
			realName() {
				if (!this.userInfo.RealName) return this.$api.msg('请完善姓名')
				if (!this.userInfo.UserPhone) return this.$api.msg('请完善手机号')
				if (!regPhone.test(this.userInfo.UserPhone)) return this.$api.msg('手机号格式不正确')
				if (!this.userInfo.IdCard) return this.$api.msg('请完善身份证号')
				if (!regIdCard.test(this.userInfo.IdCard)) return this.$api.msg('身份证号格式不正确')

				if (!this.FrontIdPhoto) return this.$api.msg('请上传身份证件')
				if (!this.ReverseIdOPhoto) return this.$api.msg('请上传身份证件')

				// 判断是否认证 和认证方式
				if (this.SignType == 1) {
					// 人脸认证
					this.facePass()
				} else {

					// 百度验证已通过 直接调用保存
					// 人脸识别
					if (this.options.flag) this.certification()
					// 二要素
					if (this.SignType == 0) {
						this.baiduPass(this.userInfo.RealName, this.userInfo.IdCard)
						return
					} else if (this.SignType == 2) {
						// 三要素
						this.threeEle()
						return
					} else {
						uni.showToast({
							icon: 'none',
							title: '请扫描二维码确认企业认证方式'
						})
						return
					}
				}
			},

			setIdCardRequest() {
				this.$http('post', '/Base_Manage/Base_User/UpdateUserRealname', {
					// 用户id
					"Id": this.userInfo.Id,
					// 身份证号
					"IdCard": this.userInfo.IdCard,
					// 身份证正面
					"FrontIdPhoto": this.FrontIdPhoto,
					// 身份证反面
					"ReverseIdOPhoto": this.ReverseIdOPhoto,
				}).then(res => {
					if (res.Success) {
						// 重新存储用户信息
						this.op()
					} else this.$api.msg(res.Msg)
				})
			},

			// 用户信息
			op() {
				if(uni.getStorageSync('flag')==false) return
				this.$http('post', '/Base_Manage/Home/GetOperatorInfo').then(res => {
					if (res.Success) {
						uni.setStorageSync('userInfo', res.Data.UserInfo)
						// setTimeout(function(){
						// 	uni.navigateBack({
						// 	  delta: 1
						// 	})
						// },1000)
					}
				})
			}
		}
	}
</script>

<style lang="less">
	.active {
		opacity: 0.4;
	}

	.container {
		.idcardFan {
			margin-top: 35rpx;
		}

		.idcardZheng,
		.idcardFan {
			width: 460rpx;
			height: 300rpx;
			display: flex;
			flex-direction: column;
			background: #fff;
			border-radius: 15rpx;

			.img {
				flex: 8
			}

			.imgText {
				flex: 2;
				background-color: #007aff;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				border-bottom-left-radius: 15rpx;
				border-bottom-right-radius: 15rpx;
			}
		}
	}
</style>